package com.kll.tv.views.fragment.main

import android.content.Intent
import android.graphics.Color
import android.view.KeyEvent
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.bumptech.glide.Glide
import com.google.gson.Gson
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.GetAdsResponse
import com.kll.carolinehmibiz.net.bean.GetSystemMenuResponse
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.HomePageProtocol
import com.kll.carolinehmibiz.presentation.presenter.HomePagePresenter
import com.kll.tv.R
import com.kll.tv.base.views.MainBaseFragment
import com.kll.tv.databinding.FragmentMainHomepageBinding
import com.kll.tv.utils.AppToast
import com.kll.carolinehmibiz.base.utils.L
import com.kll.tv.views.*
import com.kll.tv.views.adapter.BannerAdapter
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.constants.IndicatorGravity
import com.zhpan.bannerview.constants.PageStyle
import com.zhpan.indicator.enums.IndicatorSlideMode
import com.zhpan.indicator.enums.IndicatorStyle


/**
 * ====================================================
 * Created by Ziliang Cai on 2021/12/7 22:19
 * <a href="mailto:752777456@qq.com">Contact me</a>
 * ====================================================
 */
class MainHomePageFragmengt : MainBaseFragment<HomePagePresenter>(), HomePageProtocol.IView {
    private lateinit var binding: FragmentMainHomepageBinding
    private var llMenus = arrayListOf<LinearLayout>()
    private var ivMenus = arrayListOf<ImageView>()
    private var tvMenus = arrayListOf<TextView>()
    private var menuItems = arrayListOf<View>()
    private var mMenuDatas: ArrayList<GetSystemMenuResponse>? = null
    private lateinit var mViewPager: BannerViewPager<GetAdsResponse.AdsBean>

    override fun createPresenter(): HomePagePresenter {
        return HomePagePresenter(requireContext(), this)
    }


    override fun initViewBinding(): View {
        binding = FragmentMainHomepageBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun init() {
        llMenus.add(binding.llHealthyLife)
        llMenus.add(binding.llPreventTest)
        llMenus.add(binding.llMedicalRecovery)
        llMenus.add(binding.llIllnessManage)
        llMenus.add(binding.llStudyChina)
        llMenus.add(binding.llMoneyManage)
        llMenus.add(binding.llTravelLeisure)
        llMenus.add(binding.llOldCollege)
        llMenus.add(binding.llFamilyFriends)

        // 图标
        ivMenus.add(binding.ivHealthyLife)
        ivMenus.add(binding.ivPreventTest)
        ivMenus.add(binding.ivMedicalRecovery)
        ivMenus.add(binding.ivIllnessManage)
        ivMenus.add(binding.ivStudyChina)
        ivMenus.add(binding.ivMoneyManage)
        ivMenus.add(binding.ivTravelLeisure)
        ivMenus.add(binding.ivOldCollege)
        ivMenus.add(binding.ivFamilyFriends)

        // 文字
        tvMenus.add(binding.tvHealthyLife)
        tvMenus.add(binding.tvPreventTest)
        tvMenus.add(binding.tvMedicalRecovery)
        tvMenus.add(binding.tvIllnessManage)
        tvMenus.add(binding.tvStudyChina)
        tvMenus.add(binding.tvMoneyManage)
        tvMenus.add(binding.tvTravelLeisure)
        tvMenus.add(binding.tvOldCollege)
        tvMenus.add(binding.tvFamilyFriends)

        menuItems.add(binding.vHealthyLifeItem)
        menuItems.add(binding.vPreventTest)
        menuItems.add(binding.vMedicalRecovery)
        menuItems.add(binding.vIllnessManage)
        menuItems.add(binding.vStudyChina)
        menuItems.add(binding.vMoneyManage)
        menuItems.add(binding.vTravelLeisure)
        menuItems.add(binding.vOldCollege)
        menuItems.add(binding.vFamilyFriends)
        initBVP()
        initListener()
        mPresenter.getHomePageAds()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)

        if(!hidden) {
            loadData()
        }
    }

    private fun initBVP() {
        mViewPager = binding.bvpBanner as BannerViewPager<GetAdsResponse.AdsBean>
        mViewPager.apply {
            setLifecycleRegistry(lifecycle)
            adapter = BannerAdapter()
            setIndicatorStyle(IndicatorStyle.CIRCLE) // 指标样式
            setIndicatorSliderColor(Color.parseColor("#9FA0A0"), Color.parseColor("#00374D"))
            setIndicatorSlideMode(IndicatorSlideMode.WORM) // 指标滑块模式
            setIndicatorView(binding.changeIndicator) // 自定义指标
            setIndicatorGravity(IndicatorGravity.CENTER)
            setIndicatorSliderWidth(14) // 指标宽
            setIndicatorHeight(14) // 指标高
            setIndicatorSliderGap(16) // 指标间的距离
            setPageStyle(PageStyle.MULTI_PAGE_OVERLAP)
            setRevealWidth(264, 264)
            setOnPageClickListener { view, i -> itemClick(i) }
            setScrollDuration(1000)
            setInterval(3000)
            create()
        }
    }

    private fun itemClick(position: Int) {
        if (position != binding.bvpBanner.currentItem) {
            binding.bvpBanner.setCurrentItem(position, true)
        }
        L.d("TAG", "itemClick: ${position}")
    }


    private var loadDataIsBusying = false
    fun loadData() {
        if(loadDataIsBusying || mPresenter == null) return
        loadDataIsBusying = true
        L.d("TAG", "getSystemMenuSuccessed: ${Gson().toJson(mMenuDatas)}")
        if(mMenuData != null) {
            mPresenter.loadSystemMenu(mMenuData.menu_id)
        }
    }

    private fun initListener() {
        llMenus.forEach {
            it.setOnClickListener {
                var index = llMenus.indexOf(it)
                showMenusDetail(index)

            }
            it.setOnFocusChangeListener { v, hasFocus ->
                var index = llMenus.indexOf(it)
                if (hasFocus) {
                    menuItems[index].setBackgroundResource(R.drawable.bg_homepage_item_foc)
                } else {
                    menuItems[index].setBackgroundResource(R.drawable.bg_homepage_item_nor)
                }
            }
        }
    }

    private fun showMenusDetail(index: Int) {
        var intent = Intent();

        intent.setClass(requireContext(), SecondaryMenuActivity::class.java)
        intent.putExtra("menuId", mMenuDatas!![index].menu_id)
        intent.putExtra("menuTitle", mMenuDatas!![index].name)

        startActivity(intent)
    }

    fun onKeyDownChild(keyCode: Int, event: KeyEvent?) {
//        val count = binding.tvBanner.itemCount
//        when (keyCode) {
//            KeyEvent.KEYCODE_DPAD_LEFT -> {
//                var prev = (binding.tvBanner.currentItem -1) % count
//                if (prev == 0) {
//                    prev = binding.tvBanner.realCount
//                } else if (prev == count - 1) {
//                    prev = 1
//                }
//                binding.tvBanner.setCurrentItem(prev, true)
//            }
//            KeyEvent.KEYCODE_DPAD_RIGHT -> {
//                var next = (binding.tvBanner.currentItem + 1) % count
//                if (next == 0) {
//                    next = binding.tvBanner.realCount
//                } else if (next == count - 1) {
//                    next = 1
//                }
//                binding.tvBanner.setCurrentItem(next, true)
//            }
//        }
//        // 如果没有设置指示器，就不用执行下面两行
//        val real = BannerUtils.getRealPosition(binding.tvBanner.isInfiniteLoop(), binding.tvBanner.currentItem, binding.tvBanner.realCount)
//        binding.tvBanner.indicator.onPageSelected(real)
    }

    /**
     * 获取轮播图成功回调
     */
    override fun getHomePageAdsSuccessed(data: GetAdsResponse) {
        mViewPager.refreshData(data.content)
    }

    /**
     * 获取轮播图失败回调
     */
    override fun getHomePageAdsFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(context!!).updateUserToken(data.token)
                    mPresenter.getHomePageAds()
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

    /**
     * 加载菜单成功
     */
    override fun getSystemMenuSuccessed(menus: ArrayList<GetSystemMenuResponse>) {


        mMenuDatas = menus
        L.d("TAG", "getSystemMenuSuccessed: ${Gson().toJson(mMenuDatas)}")
        for(index in llMenus.indices) {
            if(menus.size <= index) {
                llMenus[index].visibility = View.GONE
            } else {
                llMenus[index].visibility = View.VISIBLE
                tvMenus[index].text = menus[index].name
                Glide.with(requireContext()).load(menus[index].icon).into(ivMenus[index])
            }
        }

    }

    /**
     * 加载菜单失败
     */
    override fun getSystemMenuFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        loadDataIsBusying = false
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(context!!).updateUserToken(data.token)
                    mPresenter.loadSystemMenu(mMenuData.menu_id)
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

}